package com.hwz.gulimall.ware.service.impl;

import com.hwz.common.constant.WareConstant;
import com.hwz.gulimall.ware.entity.PurchaseDetailEntity;
import com.hwz.gulimall.ware.service.PurchaseDetailService;
import com.hwz.gulimall.ware.service.WareInfoService;
import com.hwz.gulimall.ware.vo.DonePurchaseDetailVo;
import com.hwz.gulimall.ware.vo.DonePurchaseVo;
import com.hwz.gulimall.ware.vo.MergePurchaseVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hwz.common.utils.PageUtils;
import com.hwz.common.utils.Query;

import com.hwz.gulimall.ware.dao.PurchaseDao;
import com.hwz.gulimall.ware.entity.PurchaseEntity;
import com.hwz.gulimall.ware.service.PurchaseService;
import org.springframework.web.bind.annotation.RequestBody;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {

    @Autowired
    PurchaseDetailService purchaseDetailService;

    @Autowired
    private WareInfoService wareInfoService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryUnreceivePage(Map<String, Object> params) {

        IPage<PurchaseEntity> page = this.page(new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>().eq("status", WareConstant.PurchaseStatusEnum.CREATED.getCode()).or().eq("status", WareConstant.PurchaseStatusEnum.ASSIGNED.getCode()));



        return new PageUtils(page);
    }

    @Override
    public void merge(MergePurchaseVo mergePurchaseVo) {

        if ( mergePurchaseVo.getPurchaseId() == null  ){
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setCreateTime(new Date());
            purchaseEntity.setUpdateTime(new Date());
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.CREATED.getCode());
            this.save(purchaseEntity);
            mergePurchaseVo.setPurchaseId(purchaseEntity.getId());
        }else {
            PurchaseEntity purchaseEntity = this.getById(mergePurchaseVo.getPurchaseId());
            if ( purchaseEntity.getStatus() != WareConstant.PurchaseStatusEnum.CREATED.getCode() && purchaseEntity.getStatus() != WareConstant.PurchaseStatusEnum.ASSIGNED.getCode()){
                throw new RuntimeException("采购单状态必须为新建或者已分配");
            }
        }



        List<Long> items = mergePurchaseVo.getItems();
        List<PurchaseDetailEntity> collect = items.stream().map(item -> {
            PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
            purchaseDetailEntity.setId(item);
            purchaseDetailEntity.setPurchaseId(mergePurchaseVo.getPurchaseId());
            purchaseDetailEntity.setStatus(WareConstant.PurchaseStatusEnum.ASSIGNED.getCode());

            return purchaseDetailEntity;
        }).collect(Collectors.toList());

        purchaseDetailService.updateBatchById(collect);

        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(mergePurchaseVo.getPurchaseId());
        purchaseEntity.setUpdateTime(new Date());
        this.updateById(purchaseEntity);


    }
    //领取采购单
    @Override
    public void received(List<Long> ids) {
        //根据id获取采购单

        List<PurchaseEntity> list = this.listByIds(ids);

        List<PurchaseEntity> collect = list.stream().filter(item -> {
            return item.getStatus() == WareConstant.PurchaseStatusEnum.CREATED.getCode() || item.getStatus() == WareConstant.PurchaseStatusEnum.ASSIGNED.getCode();
        }).map(item -> {
            item.setStatus(WareConstant.PurchaseStatusEnum.RECEIVE.getCode());
            item.setUpdateTime(new Date());
            return item;
        }).collect(Collectors.toList());

        //更新这些采购单状态
        this.updateBatchById(collect);

        //更新采购需求的状态
        collect.forEach(item -> {
            List<PurchaseDetailEntity> detailEntities = purchaseDetailService.list(new QueryWrapper<PurchaseDetailEntity>().eq("purchase_id", item.getId()));
            List<PurchaseDetailEntity> detailList = detailEntities.stream().map(detail -> {
                PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
                purchaseDetailEntity.setId(detail.getId());
                purchaseDetailEntity.setStatus(WareConstant.PurchaseStatusEnum.RECEIVE.getCode());
                return purchaseDetailEntity;
            }).collect(Collectors.toList());
            purchaseDetailService.updateBatchById(detailList);
        });
    }

    @Override
    public void done( DonePurchaseVo purchaseVo) {
        Boolean finish = true;
        PurchaseEntity basePurchaseEntity = this.getById(purchaseVo.getId());
        if (basePurchaseEntity.getStatus() != WareConstant.PurchaseStatusEnum.RECEIVE.getCode() && basePurchaseEntity.getStatus() != WareConstant.PurchaseStatusEnum.ASSIGNED.getCode()){
            throw new RuntimeException("采购单状态必须为已领取或者新建");
        }


        ArrayList<PurchaseDetailEntity> purchaseDetailEntities = new ArrayList<>();
        for (DonePurchaseDetailVo item : purchaseVo.getItems()) {
            PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
            if (item.getStatus() == WareConstant.PurchaseDetailStatusEnum.HASERROR.getCode()) {
                finish = false;
                detailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.HASERROR.getCode());
            }else {
                detailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.FINISH.getCode());
                //修改商品库存
                //1、查询采购单详情
                PurchaseDetailEntity detail = purchaseDetailService.getById(item.getItemId());
                //2、查询库存详情
                wareInfoService.addStock(detail.getSkuId(),detail.getWareId(),detail.getSkuNum());

            }
            detailEntity.setId(item.getItemId());
            //改变每个采购需求的状态
            purchaseDetailEntities.add(detailEntity);
        }
        purchaseDetailService.updateBatchById(purchaseDetailEntities);


        //改变采购单状态
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(purchaseVo.getId());
        purchaseEntity.setUpdateTime(new Date());
        purchaseEntity.setStatus(finish ? WareConstant.PurchaseStatusEnum.FINISH.getCode() : WareConstant.PurchaseStatusEnum.HASERROR.getCode());
        this.updateById(purchaseEntity);



    }

}